package org.example.demo.util;


import io.jsonwebtoken.*;

import java.util.*;

public class JWTUtils {
    private static final String KEY = "kfcvme40";

    // 默认设置token有效期为一个小时
    private static final long expirationTime = 1000 * 60 * 60;

    /**
     * 生成Token  header.payload.sign
     */
    public static String genToken(Map<String,Object> data) {
        JwtBuilder builder = Jwts.builder();
        String jwtToken = builder
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .setClaims(data)
                .setSubject("user")
                .setExpiration(new Date(System.currentTimeMillis()+expirationTime))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,KEY)
                .compact();
        return jwtToken;
    }

    public static Claims parseToken(String token) {
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(KEY).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims;
    }

    public static boolean checkToken(String token) {
        JwtParser parser = Jwts.parser();
        try {
            Jws<Claims> claimsJws = parser.setSigningKey(KEY).parseClaimsJws(token);
        } catch (Exception e) {
            // jwt解析异常，说明过期了
            return false;
        }
        return true;
    }
}
